package top.cluski.tokendemo.service.impl;

import cn.hutool.jwt.JWTUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import top.cluski.tokendemo.domain.LoginUser;
import top.cluski.tokendemo.domain.ResponseResult;
import top.cluski.tokendemo.domain.User;
import top.cluski.tokendemo.service.LoginService;
import top.cluski.tokendemo.utils.RedisUtil;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    RedisUtil redisUtil;

    @Override
    public ResponseResult login(User user) {
        // AuthenticationManager authenticate 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果认证没有通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        // 如果认证通过，使用userId生成一个jwt，jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long userId = loginUser.getUser().getId();

        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("uid", userId);
                put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 2);
            }
        };
        String token = JWTUtil.createToken(map, "softwise".getBytes());
        // 把完整的用户信息存入Redis，userId作为key
        redisUtil.setCacheObject("login:" + String.valueOf(userId), loginUser);
        return new ResponseResult(200, "登录成功", new HashMap<String, String>() {
            {
                put("token", token);
            }
        });
    }

    @Override
    public ResponseResult logout() {
        // 获取SecurityContextHolder中的userId
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = loginUser.getUser().getId();

        // 删除Redis中的值
        redisUtil.deleteObject("login:" + String.valueOf(userId));
        return new ResponseResult(200, "退出成功");
    }
}
